package cn.xspace.wnx.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.ConfirmDialog;
import com.xspace.android.xafcommon.view.sdlv.DragListView;
import com.xspace.android.xafcommon.view.sdlv.Menu;
import com.xspace.android.xafcommon.view.sdlv.MenuItem;
import com.xspace.android.xafcommon.view.sdlv.SlideAndDragListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.adapter.NewFriendsAdapter;
import cn.xspace.wnx.db.MyNewFriendDao;
import cn.xspace.wnx.entity.NewFriendBean;
import cn.xspace.wnx.fragment.AddressBookFragment;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class NewFriendActivity extends BaseActivity implements SlideAndDragListView.OnListItemClickListener,
        SlideAndDragListView.OnMenuItemClickListener, DragListView.OnDragListener {

    private TitleBar mTitleBar;
    private SlideAndDragListView mListView;
    private Menu mMenu;
    private ArrayList<NewFriendBean> mDataList;
    private NewFriendsAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void getIntentData() {
        super.getIntentData();
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_new_friend);
    }

    @Override
    protected void initFindViewById() {
        mTitleBar = (TitleBar) findViewById(R.id.new_friend_titleBar);
        mTitleBar.setTitle(getResources().getString(R.string.friend_application));
        mTitleBar.showRightText();
        mTitleBar.setRightLayoutTextView(getResources().getString(R.string.add_friend));
        mListView = (SlideAndDragListView) findViewById(R.id.sdlv_new_firend);
        initMenu();
        mListView.setMenu(mMenu);
    }

    /**
     * 侧滑弹出的菜单内的条目
     */
    private void initMenu() {
        mMenu = new Menu(true, true);
        mMenu.addItem(new MenuItem.Builder().setWidth(ResourceUtils.getDimens(R.dimen.space_80))
                .setBackground(ResourceUtils.getDrawable(R.drawable.bg_menu_delete))
                .setDirection(MenuItem.DIRECTION_RIGHT)
                .setText(getResources().getString(R.string.delete))
                .setTextColor(Color.WHITE)
                .build());
    }

    @Override
    protected void initData() {
        clearUnreadCount();
        mDataList = new ArrayList<>();
        adapter = new NewFriendsAdapter(mContext, mDataList);
        mListView.setAdapter(adapter);
        mListView.setOnDragListener(this, mDataList);
        getLocalData();
    }

    private void clearUnreadCount() {
        MyNewFriendDao.getInstance().clearUnReadCount();
        AddressBookFragment.refreshUnreadCount = true; //刷新两个界面的未读数字
        MyFriendActivity.refreshUnreadCount = true;
    }

    private void getLocalData() {
        MyNewFriendDao.getInstance().getNewFriendList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ArrayList<NewFriendBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(ArrayList<NewFriendBean> newFriendBeen) {
                        mDataList.clear();
                        mDataList.addAll(newFriendBeen);
                        refreshList();
                    }
                });
    }

    private void refreshList() {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void initEvent() {
        mListView.setOnListItemClickListener(this);
        mListView.setOnMenuItemClickListener(this);
        adapter.setConfirmClickListener(new NewFriendsAdapter.IConfirmClickListener() {
            @Override
            public void onConfirmClick(NewFriendBean bean, int position) {
                requestConfirm(bean);
            }
        });
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SearchForAddFriendActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 同意好友申请
     *
     * @param bean
     */
    private void requestConfirm(final NewFriendBean bean) {
        showWaitDialog();
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", MyInfoUtil.getMyUserid(mContext));
        requestMap.put("friend_id", bean.user_id);
        registerSubscription(OkHttpManager.getInstance().commonRequest(Constants.ADD_FRIEND_RESPONSE, requestMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, e.getMessage());
                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        hideWaitDialog();
                        bean.add_status = 1;
                        T.showShort(mContext, "添加好友成功");
                        MyNewFriendDao.getInstance().updateFriendStatus(bean);
//                        MyFriendActivity.refreshData = true;
                        //发送到我的好友界面，刷新界面
                        Map<String, Object> map = new HashMap<>();
                        map.put(EventBusConstant.TYPE, EventBusConstant.NEW_FRIEND_PUSH);
                        map.put(EventBusConstant.ACTION_KEY, EventBusConstant.NEW_FRIEND_FINISH);
                        EventBus.getDefault().post(map);
                        refreshList();
                    }
                }));
    }

    @Override
    public void onListItemClick(View v, int position) {
        int index = position - mListView.getHeaderViewsCount();
        NewFriendBean bean = mDataList.get(index);
        Intent mIntent = new Intent(mContext, PersonCardActivity.class);
        mIntent.putExtra(PersonCardActivity.FRIEND_ID, bean.user_id);
        //不是好友并且已添加状态为空,已添加过一次但是后来又删除了的不算,没次重新申请则重置添加状态
        if (bean.add_status == 0 && TextUtils.isEmpty(bean.is_add)) {
            mIntent.putExtra(PersonCardActivity.ADD_FRIEND, true);
            mIntent.putExtra(PersonCardActivity.ADD_FRIEND_DESC, bean.req_desc);
        }
        startActivity(mIntent);
    }

    @Override
    public int onMenuItemClick(View v, int itemPosition, int buttonPosition, int direction) {
        switch (direction) {
            case MenuItem.DIRECTION_LEFT:
                switch (buttonPosition) {
                    case 0:
                        return Menu.ITEM_NOTHING;
                    case 1:
                        return Menu.ITEM_SCROLL_BACK;
                }
                break;
            case MenuItem.DIRECTION_RIGHT:
                switch (buttonPosition) {
                    case 0:
                        showDeleteDialog(itemPosition);
                        // TODO 删除好友申请
                        return Menu.ITEM_SCROLL_BACK;
                    case 1:
                        return Menu.ITEM_SCROLL_BACK;
                }
        }
        return Menu.ITEM_NOTHING;
    }

    private void showDeleteDialog(final int position) {
        new ConfirmDialog.Builder(mContext)
                .setTitleMsg(getResources().getString(R.string.delete_friend_application))
                .setContentVisible(View.GONE)
                .setLeftText(ResourceUtils.getString(R.string.think_again_and_again))
                .setRightText(ResourceUtils.getString(R.string.button_ok))
                .setRightListener(new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
                        deleteItem(position);
                    }
                })
                .setListener()
                .show();
    }

    /**
     * 删除某个好友申请
     *
     * @param position
     */
    private void deleteItem(final int position) {
        NewFriendBean bean = mDataList.get(position);
        registerSubscription(MyNewFriendDao.getInstance().deleteOneFriendApplication(bean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Integer integer) {
                        mDataList.remove(position);
                        refreshList();
                    }
                }));
    }

    @Override
    public void onDragViewStart(int position) {

    }

    @Override
    public void onDragViewMoving(int position) {

    }

    @Override
    public void onDragViewDown(int position) {

    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        LogUtil.d(inParam.toString());
        if (EventBusConstant.NEW_FRIEND_PUSH.equals(inParam.get(EventBusConstant.TYPE))) {
            if (EventBusConstant.NEW_FRIEND_PUSH_BEAN.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                NewFriendBean bean = (NewFriendBean) inParam.get(EventBusConstant.NEW_FRIEND_PUSH_BEAN);
                if (bean != null) { //新的请求
                    boolean isUpdate = false;
                    for (NewFriendBean newFriendBean : mDataList) {
                        if (TextUtils.equals(newFriendBean.user_id, bean.user_id)) { //更新验证信息
                            isUpdate = true;
                            newFriendBean.req_desc = bean.req_desc;
                            newFriendBean.add_status = bean.add_status;
                            break;
                        }
                    }
                    if (!isUpdate) { //如果不是更新信息
                        mDataList.add(0, bean);
                    }
                    refreshList();
                }
            } else if (EventBusConstant.NEW_FRIEND_FINISH.equals(inParam.get(EventBusConstant.ACTION_KEY))) {//添加完成的请求
                NewFriendBean bean = (NewFriendBean) inParam.get(EventBusConstant.NEW_FRIEND_PUSH_BEAN);
                if (bean != null) {
                    for (NewFriendBean newFriendBean : mDataList) {
                        if (TextUtils.equals(newFriendBean.user_id, bean.user_id)) { //更新添加信息
                            newFriendBean.add_status = bean.add_status;
                            break;
                        }
                    }
                    refreshList();
                }
            }
        }
    }
}
